<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 后台公共文件
 * 主要定义后台公共函数库
 */

/* 解析列表定义规则*/

function get_list_field($data, $grid,$model){

	// 获取当前字段数据
    foreach($grid['field'] as $field){
        $array  =   explode('|',$field);
        $temp  =	$data[$array[0]];
        // 函数支持
        if(isset($array[1])){
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]]    =   $temp;
    }
    if(!empty($grid['format'])){
        $value  =   preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data2){return $data2[$match[1]];}, $grid['format']);
    }else{
        $value  =   implode(' ',$data2);
    }

	// 链接支持
	if(!empty($grid['href'])){
		$links  =   explode(',',$grid['href']);
        foreach($links as $link){
            $array  =   explode('|',$link);
            $href   =   $array[0];
            if(preg_match('/^\[([a-z_]+)\]$/',$href,$matches)){
                $val[]  =   $data2[$matches[1]];
            }else{
                $show   =   isset($array[1])?$array[1]:$value;
                // 替换系统特殊字符串
                $href	=	str_replace(
                    array('[DELETE]','[EDIT]','[MODEL]'),
                    array('del?ids=[id]&model=[MODEL]','edit?id=[id]&model=[MODEL]',$model['id']),
                    $href);

                // 替换数据变量
                $href	=	preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data){return $data[$match[1]];}, $href);

                $val[]	=	'<a href="'.U($href).'">'.$show.'</a>';
            }
        }
        $value  =   implode(' ',$val);
	}
    return $value;
}

function get_form_fields($fields = array()){
  $values = array();
  foreach($fields as $i){
    $values[$i] = I($i);
  }
  return $values;
}

function create_guid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $uuid =
    substr($charid, 0, 8)
    .substr($charid, 8, 4)
    .substr($charid,12, 4)
    .substr($charid,16, 4)
    .substr($charid,20,12)
    ;// "}"
    return $uuid;
}

// 获取模型名称
function get_model_by_id($id){
    return $model = M('Model')->getFieldById($id,'title');
}

// 获取属性类型信息
function get_attribute_type($type=''){
    // TODO 可以加入系统配置
    static $_type = array(
        'num'       =>  array('数字','int(10) UNSIGNED NOT NULL'),
        'string'    =>  array('字符串','varchar(255) NOT NULL'),
        'textarea'  =>  array('文本框','text NOT NULL'),
        'datetime'  =>  array('时间','int(10) NOT NULL'),
        'bool'      =>  array('布尔','tinyint(2) NOT NULL'),
        'select'    =>  array('枚举','char(50) NOT NULL'),
    	'radio'		=>	array('单选','char(10) NOT NULL'),
    	'checkbox'	=>	array('多选','varchar(100) NOT NULL'),
    	'editor'    =>  array('编辑器','text NOT NULL'),
    	'picture'   =>  array('上传图片','int(10) UNSIGNED NOT NULL'),
    	'file'    	=>  array('上传附件','int(10) UNSIGNED NOT NULL'),
    );
    return $type?$_type[$type][0]:$_type;
}

/**
 * 获取对应状态的文字信息
 * @param int $status
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_status_title($status = null){
    if(!isset($status)){
        return false;
    }
    switch ($status){
        case -1 : return    '已删除';   break;
        case 0  : return    '禁用';     break;
        case 1  : return    '正常';     break;
        case 2  : return    '待审核';   break;
        default : return    false;      break;
    }
}

// 获取数据的状态操作
function show_status_op($status) {
    switch ($status){
        case 0  : return    '启用';     break;
        case 1  : return    '禁用';     break;
        case 2  : return    '审核';		break;
        default : return    false;      break;
    }
}

/**
 * 获取文档的类型文字
 * @param string $type
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_document_type($type = null){
    if(!isset($type)){
        return false;
    }
    switch ($type){
        case 1  : return    '目录'; break;
        case 2  : return    '主题'; break;
        case 3  : return    '段落'; break;
        default : return    false;  break;
    }
}

/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_type($type=0){
    $list = C('CONFIG_TYPE_LIST');
    return $list[$type];
}

/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_storage($type=0){
    $list = C('CONFIG_STORAGE_LIST');
    return $list[$type];
}

/**
 * 获取配置的分组
 * @param string $group 配置分组
 * @return string
 */
function get_config_group($group=0){
    $list = C('CONFIG_GROUP_LIST');
    return $group?$list[$group]:'';
}

/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map  映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @author 朱亚杰 <zhuyajie@topthink.net>
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 */
function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'已下架',2=>'未审核',3=>'草稿',1010=>'创建申请',1011=>'正在采购',1012=>'已采购',1013=>'提交财务',1014=>'财务确认完成，采购完成'))) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        foreach ($map as $col=>$pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

function int_to_string_loss(&$data,$map=array('status'=>array(0=>'未审核',-1=>'审核不通过',1=>'审核通过'))) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        foreach ($map as $col=>$pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

/**
 * 动态扩展左侧菜单,base.html里用到
 * @author 朱亚杰 <zhuyajie@topthink.net>
 */
function extra_menu($extra_menu,&$base_menu){
    foreach ($extra_menu as $key=>$group){
        if( isset($base_menu['child'][$key]) ){
            $base_menu['child'][$key] = array_merge( $base_menu['child'][$key], $group);
        }else{
            $base_menu['child'][$key] = $group;
        }
    }
}

/**
 * 获取参数的所有父级分类
 * @param int $cid 分类id
 * @return array 参数分类和父类的信息集合
 * @author huajie <banhuajie@163.com>
 */
function get_parent_category($cid){
    if(empty($cid)){
        return false;
    }
    $cates  =   M('Category')->where(array('status'=>1))->field('id,title,pid')->order('sort')->select();
    $child  =   get_category($cid);	//获取参数分类的信息
    $pid    =   $child['pid'];
    $temp   =   array();
    $res[]  =   $child;
    while(true){
        foreach ($cates as $key=>$cate){
            if($cate['id'] == $pid){
                $pid = $cate['pid'];
                array_unshift($res, $cate);	//将父分类插入到数组第一个元素前
            }
        }
        if($pid == 0){
            break;
        }
    }
    return $res;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 获取当前分类的文档类型
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_type_bycate($id = null){
    if(empty($id)){
        return false;
    }
    $type_list  =   C('DOCUMENT_MODEL_TYPE');
    $model_type =   M('Category')->getFieldById($id, 'type');
    $model_type =   explode(',', $model_type);
    foreach ($type_list as $key=>$value){
        if(!in_array($key, $model_type)){
            unset($type_list[$key]);
        }
    }
    return $type_list;
}

/**
 * 获取当前文档的分类
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_cate($cate_id = null){
    if(empty($cate_id)){
        return false;
    }
    $cate   =   M('Category')->where('id='.$cate_id)->getField('title');
    return $cate;
}

 // 分析枚举类型配置值 格式 a:名称1,b:名称2
function parse_config_attr($string) {
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if(strpos($string,':')){
        $value  =   array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k]   = $v;
        }
    }else{
        $value  =   $array;
    }
    return $value;
}

// 获取子文档数目
function get_subdocument_count($id=0){
    return  M('Document')->where('pid='.$id)->count();
}



 // 分析枚举类型字段值 格式 a:名称1,b:名称2
 // 暂时和 parse_config_attr功能相同
 // 但请不要互相使用，后期会调整
function parse_field_attr($string) {
    if(0 === strpos($string,':')){
        // 采用函数定义
        return   eval(substr($string,1).';');
    }
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if(strpos($string,':')){
        $value  =   array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k]   = $v;
        }
    }else{
        $value  =   $array;
    }
    return $value;
}

/**
 * 获取行为数据
 * @param string $id 行为id
 * @param string $field 需要获取的字段
 * @author huajie <banhuajie@163.com>
 */
function get_action($id = null, $field = null){
	if(empty($id) && !is_numeric($id)){
		return false;
	}
	$list = S('action_list');
	if(empty($list[$id])){
		$map = array('status'=>array('gt', -1), 'id'=>$id);
		$list[$id] = M('Action')->where($map)->field(true)->find();
	}
	return empty($field) ? $list[$id] : $list[$id][$field];
}

/**
 * 根据条件字段获取数据
 * @param mixed $value 条件，可用常量或者数组
 * @param string $condition 条件字段
 * @param string $field 需要返回的字段，不传则返回整个数据
 * @author huajie <banhuajie@163.com>
 */
function get_document_field($value = null, $condition = 'id', $field = null){
	if(empty($value)){
		return false;
	}

	//拼接参数
	$map[$condition] = $value;
	$info = M('Model')->where($map);
	if(empty($field)){
		$info = $info->field(true)->find();
	}else{
		$info = $info->getField($field);
	}
	return $info;
}

/**
 * 获取行为类型
 * @param intger $type 类型
 * @param bool $all 是否返回全部类型
 * @author huajie <banhuajie@163.com>
 */
function get_action_type($type, $all = false){
	$list = array(
		1=>'系统',
		2=>'用户',
	);
	if($all){
		return $list;
	}
	return $list[$type];
}

/**
 * 调用http接口
 * @param $url 接口地址
 * @param $data 调用的数据
 * @return mixed
 */
function post_data($url,$data=array()){

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

    $rsp = curl_exec($ch);

    curl_close($ch);
    return json_decode($rsp);
}

function get_warehouse($wid){
    $wname=M('Warehouse')->where(array('id'=>$wid))->getField('name');
    return $wname;
}

/**
 * 获得连锁店分类名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_pcategory_name($id){
    $name=M('sp_pcategory')->where(array('id'=>$id))->getField('name');
    return $name;
}
/**
 * 获得连锁店店铺名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_shop_name($id){
    $name=M('sp_shops')->where(array('id'=>$id))->getField('name');
    return $name;
}
/**
 * 获得连锁店店铺地址
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_shop_address($id){
    $address=M('sp_shops')->where(array('id'=>$id))->getField('s_address');
    return $address;
}
/**
 * 获得Status名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_status_name($status){
    switch($status){
        case -1:
            return "已删除";
            break;
        case 0:
            return "被禁用";
            break;
        case 1:
            return "正常";
            break;
        case 2:
            return "未审核";
            break;
    }
}

/**
 * 获得门店采购订货单Status名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_bookstatus_name($status){
    switch($status){
        case 0:
            return "未审核";
            break;
        case 10:
            return "审核通过,下一步等待配货";
            break;
        case 20:
            return "被商品部拒绝";
            break;
        case 30:
            return "正在配货,下一步等待发货";
            break;
        case 40:
            return "已经发货,下一步等待签收";
            break;
        case 50:
            return "已签收";
            break;
        case 60:
            return "门店拒绝";
            break;
    }
}
/**
 * 获得商品名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_product_name($id){
    $name=M('sp_product')->where(array('id'=>$id))->getField('name');
    return $name;
}
/**
 * 获得会员卡卡号
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_membercard_cardNum($id){
    $name=M('sp_membercard')->where(array('id'=>$id))->getField('cardNum');
    return $name;

}
/**
 * 获得付款方式
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_payway_name($id){
    $name=M('sp_payway')->where(array('id'=>$id))->getField('name');
    return $name;

}
/**
 * 获得门店采购订货单Status名称 1-销售，2-进货，3-退货，4-报损
* @author 曹梦龙 <138888611@qq.com>
*/
function get_sp_pstockchangetype_name($type){
    switch($type){
        case 1:
            return "销售";
            break;
        case 2:
            return "进货";
            break;
        case 3:
            return "退货";
            break;
        case 4:
            return "报损";
            break;
    }
}
/****
 * 日志记录功能
 */
function addOrderLog($id,$type,$remark,$uname){
    if(is_null($uname)){
        $uname=  get_nickname(UID);
    }

    $Log = M("operate_log"); // 实例化User对象
    $data['dataId'] = $id;
    $data['type'] = $type;
    $data['uid'] = UID;
    $data['uname'] = $uname;
    $data['remark'] = $remark;
    $data['createdate'] = NOW_TIME;
    $Log->add($data);
}
// 获取奖惩条例标题
function get_regulation_title($id){
    $name=M('regulations')->where(array('id'=>$id))->getField('title');
    return $name;
}
/**
 * 获得LBS APP名称
* @author 曹梦龙 <138888611@qq.com>
*/
function get_lbs_application_name($id){
    $name=M('lbs_application')->where(array('id'=>$id))->getField('name');
    return $name;

}
/***
 * @author Scor<1006792421@qq.com>
 * 获取商品阶段值
 */
function getperiod($pid){
    $product = M("Material_fruitclassify")->where(array('fruit_classify_no'=>$pid))->find();
    $map['fruit_classify'] = $product['fruit_classify'];
    $arr['fruit_classify_no'] = $product['fruit_classify_no'];
    $arr['per2_time'] = $product['per2_time'];
    $arr['per3_time'] = $product['per3_time'];
    return $arr;
}
function getinfo($pid){
    $res = M('Product')->where(array('id'=>$pid))->find();
    return $res;
}
/***
 * 获取物料商品仓库库存
 * @author 曹梦龙 <138888611@qq.com>
 */
function get_vinventory_count($bin){
     $cnt=M('vinventory')->where(array('BIN'=>$bin))->getField('cnt');
    return $cnt;
}
function get_next_period($periodtime,$nowtime){
    $periodtimetimestamp = strtotime($periodtime);
    $nowtimetimestamp = strtotime($nowtime);
    return ($periodtimetimestamp-$nowtimetimestamp)/(3600*24);
}
function get_report_name($report_uid){
    return M("Report_user")->where(array('id'=>$report_uid))->getfield('name');
}
/**
 * 获取物料禁用状态
 * @param $status
 * @return string
 */
function get_material_status($status){
    switch($status){
        case 0:
            return "禁用";
            break;
        case 1:
            return "正常";
            break;
        case -1:
            return "无效";
            break;
        case 9:
            return "待审核";
            break;
    }
}
/**
 * 数据库取值
 * @param $id
 * @param $table
 * @param $index
 * @param $field
 * @return mixed
 */

/***
 * 获取属性编码
 * @param $BIN
 * @param $tag
 * @return string
 *
 */
function get_no_by_tag($BIN,$tag){
    switch ($tag){
        case 'classify_no':
            return substr($BIN,0,1);
            break;
        case 'fruit_classify_no':
            return substr($BIN,1,2);
        break;
        case 'pname_no':
            return substr($BIN,3,2);
        break;
    }
}
/**
 * 获取编码对应商品数组
 * @param $BIN
 * @return mixed
 *
 */
function BIN_to_array($BIN){
    return get_name_by_id($BIN,'Material_product','BIN');
}
function list_bin_array(&$data) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        if(!isset($row['BIN'])){
            continue;
        }else{
           $data[$key]['BIN_array'] = get_name_by_id($row['BIN'],'Material_product','BIN',"");
        }
    }
    return $data;
}
function get_cnt_warn(&$data,$status) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        $cnt_low = $data[$key]['BIN_array']['cnt_low'];
        $cnt_poor = $data[$key]['BIN_array']['cnt_poor'];
        $cnt_much = $data[$key]['BIN_array']['cnt_much'];
        $cnt = $data[$key]['cnt'];
        if($row['BIN_array']['cnt_low'] == 0){
            unset($data[$key]);
            continue;
        }else{
            $low_per = intval(($cnt_low/$cnt_much)*100);
            $poor_per =  intval((($cnt_poor-$cnt_low)/$cnt_much)*100);
            $normal_per = intval((($cnt_much-$cnt_poor)/$cnt_much)*100);
            $now_per = intval(($cnt/$cnt_much)*100);
            $now_per = $now_per < 100 ? $now_per : 100;
            $arr = array('low_per'=>$low_per,'poor_per'=>$poor_per,'normal_per'=>$normal_per);
            $max = array_search(max($arr), $arr);
            $min = array_search(min($arr), $arr);
//            $arr[$max] = max($low_per,$poor_per,$normal_per)-6;
//            $arr[$min] = min($low_per,$poor_per,$normal_per)+6;
            $data[$key]['low_per'] = $arr['low_per'];
            $data[$key]['poor_per'] = $arr['poor_per'];
            $data[$key]['normal_per'] = $arr['normal_per'];
            $data[$key]['now_per'] = $now_per;
        }
        switch($status){
            case 1:
                if(!($cnt_low >= $cnt)){
                    unset($data[$key]);
                }
                break;
            case 2:
                if(!($cnt_low < $cnt&&$cnt<=$cnt_poor)){
                    unset($data[$key]);
                }
                break;
            case 3:
                if(!($cnt_poor < $cnt&&$cnt <=$cnt_much)){
                    unset($data[$key]);
                }
                break;
            case 4:
                if(!($cnt_much < $cnt)){
                    unset($data[$key]);
                }
                break;
        }
    }
    return $data;
}
function add_erp_log($module,$table,$index,$type,$detail){
    $data['module'] = $module;
    $data['table'] = $table;
    $data['index'] = $index;
    $data['type'] = $type;
    $data['detail'] = $detail;
    $data['time'] = date("YmdH",time());
    $data['UID'] = UID;
    M('Erp_log')->add($data);
}
function gr_encode($src){
    $part = substr($src,0,8);
    $part2 = substr($src,8,8);
    $y = rand(1423,9865);
    if($part2!=""){
        $y = rand(1,9);
    }
    $m = substr($part,4,2);
    $d = substr($part,6,2);
    $en_code = $m.$y.$d;
    return $part2.$en_code;
}
function son_to_mother($son,$rate){
    return round($son/$rate,2);
}
//param 空字段验证
function array_vaild($arr) {
    $index = false;
    foreach ($arr as $k => $v) {
        if ($v == '' || $v == null) {
            $index = $k;
            break;
        }
    }
    return $index;
}

function get_app_status($status){
    switch($status){
        case 0:
            return "已审核";
            break;
        case 1:
            return "待审核";
            break;
        case 2:
            return "未通过";
            break;
    }
}

function get_sp_payway($paywayID){
    $name=M('sp_payway')->where(array('id'=>$paywayID))->getField('name');
    return $name;
}

function get_sp_type($type){
    switch($type){
        case 1:
            return "销售";
            break;
        case 2:
            return "充值";
            break;
    }
}

function spec_number_format($spec,$deg=1,$times=1,$with_unit=false){
    $reg="/\d+[\.\d+]*/";
    preg_match($reg,$spec,$number);
    $unit=str_replace($number[0],"",$spec);
    $spec_number=round(floatval($number[0])*$times,$deg);
    if($with_unit){
        $output=$spec_number.$unit;
    }else{
        $output=$spec_number;
    }
    return $output;
}
function get_spec_forward_unit($spec){
    $reg="/[0-9](?=[\D]*$)/";
    preg_match($reg,$spec,$number);
    $position=strrpos($spec,$number[0]);
    return mb_substr($spec,$position+1,1,'utf-8');
}
function multi_array_sort($multi_array,$sort_key,$sort=SORT_DESC){
    if(is_array($multi_array)){
        foreach ($multi_array as $row_array){
            if(is_array($row_array)){
                $key_array[] = $row_array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_array,$sort,$multi_array);
    return $multi_array;
}

function get_subpro_department_name($id){
    $name=M('subpro_department')->where(array('id'=>$id))->getField('name');
    return $name;
}

function get_subpro_product_name($BIN){
    $name=M('subpro_product')->where(array('id'=>$BIN))->getField('pname');
    return $name;
}

function get_subpro_product_spec($BIN){
    $name=M('subpro_product')->where(array('id'=>$BIN))->getField('spec');
    return $name;
}

function get_subpro_applystatus_name($status){
    switch($status){
        case 1:
            return "未审核";
            break;
        case 2:
            return "已通过";
            break;
        case 3:
            return "未通过";
            break;
        case 4:
            return "已配货";
            break;
        case 5:
            return "已签收";
            break;
    }
}
